package component;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowAnchor;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.ui.EditorTextField;
import entity.NoteData;
import org.jetbrains.annotations.Nullable;
import persistent.DataCenter;

import javax.swing.*;
import java.awt.*;
import java.util.Vector;

public class AddNoteDialog extends DialogWrapper {
    /**
     * 标题输入框
     */
    private EditorTextField etfTitle;
    /**
     * 内容输入框
     */
    private EditorTextField etfMark;

    private Project project;


    public AddNoteDialog(Project project) {
        super(true);
        this.project=project;
        init();
        setTitle("添加笔记注释");
    }

    @Nullable
    @Override
    protected JComponent createCenterPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        etfTitle = new EditorTextField("笔记标题");
        etfMark = new EditorTextField("笔记内容");
        etfMark.setPreferredSize(new Dimension(200,100));
        panel.add(etfTitle, BorderLayout.NORTH);
        panel.add(etfMark, BorderLayout.CENTER);
        return panel;
    }

    @Override
    protected JComponent createSouthPanel() {
        JPanel panel = new JPanel(new FlowLayout());
        JButton btnAdd = new JButton("添加到笔记列表");
        //按钮点击事件处理
        btnAdd.addActionListener(e -> {
            //获取标题
            String title = etfTitle.getText();
            //获取内容
            String content = etfMark.getText();

            NoteData noteData = new NoteData();
            noteData.setContent(DataCenter.SELECTED_TEXT);
            noteData.setFileName(DataCenter.CURRENT_FILE_NAME);
            noteData.setFileType(DataCenter.CURRENT_FILE_TYPE);
            noteData.setMark(content);
            noteData.setTitle(title);
            //添加
            DataCenter.TABLE_MODEL.addRow(toStringArray(noteData));
            DataCenter.NOTE_LIST.add(noteData);
            this.close(DialogWrapper.OK_EXIT_CODE);
            ToolWindowManager windowManager = ToolWindowManager.getInstance(project);
            ToolWindow markBookWindown = windowManager.getToolWindow("MarkBookWindown");
            if (markBookWindown == null) {
                windowManager.registerToolWindow("MarkBookWindown", false, ToolWindowAnchor.RIGHT);
            }else {
                markBookWindown.show(Thread.currentThread());
            }
        });
        panel.add(btnAdd);
        return panel;
    }

    private Vector<String> toStringArray(NoteData noteData) {
        Vector<String> vector = new Vector<>();
        vector.add(noteData.getTitle());
        vector.add(noteData.getMark());
        vector.add(noteData.getFileName());
        vector.add(noteData.getContent());
        return vector;
    }
}

